package cn.arts.assumejson.algo.sort.class01;

import java.sql.SQLOutput;
import java.util.Arrays;

/**
 * Determine whether a number exists in an ordered array
 *
 * @author by <a href="mailto:ligang941012@gmail.com">gang.Li</a>
 * @since 2024/7/30 0:49
 */
public class Code04_BSExist {
    public static boolean isExist(int[] arr, int x) {
        if (arr == null || arr.length == 0) return false;
        return process(arr, x);
    }

    private static boolean process(int[] arr, int x) {
        int L = 0, mid = 0, R = arr.length - 1;

        while (L <= R) {
            mid = L + ((R - L) >> 1);
            if (arr[mid] == x) {
                return true;
            } else if (arr[mid] < x) {
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }

        return arr[mid] == x;
    }

    private static boolean process2(int[] arr, int x) {
        int L = 0, mid = 0, R = arr.length - 1;

        while (L <= R) {
            mid = L + ((R - L) >> 1);
            if (arr[mid] == x) {
                return true;
            } else if (arr[mid] > x) {
                R = mid - 1;
            } else {
                L = mid + 1;
            }
        }
        return arr[mid] == x;
    }

    // for test
    public static boolean test(int[] arr, int x) {
        for (int i : arr) {
            if (i == x) {
                return true;
            }
        }
        return false;
    }

    // for test
    public static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[(int) ((maxSize + 1) * Math.random())];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random());
        }
        return arr;
    }

    public static void main(String[] args) {
        int testTime = 50000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = false;
        for (int i = 0; i < testTime; i++) {
            final int[] arr = generateRandomArray(maxSize, maxValue);
            Arrays.sort(arr);
            int randomValue = (int) ((maxValue + 1) * Math.random()) - (int) ((maxValue + 1) * Math.random());
            if (isExist(arr, randomValue) != test(arr, randomValue)) {
                System.out.println(randomValue);
                System.out.println(Arrays.toString(arr));
                System.out.println(isExist(arr, randomValue));
                System.out.println(test(arr, randomValue));
                succeed = false;
                break;
            }
            succeed = true;
        }
        System.out.println(succeed ? "NICE!!!" : "FUCKING!!!");
    }
}
